package hn.cch.grammar.net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Created by CCH on 2018/5/7.
 */
public class Client {
    private int port;
    private InetAddress address;
    private DatagramSocket client;

    public Client() {
        try {
            client = new DatagramSocket();
        } catch (SocketException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("客户端连接：" + client);
    }


    public static void main(String[] args) {
        Client client = new Client();
        client.send();


    }

    public void send() {
        port = 8080;
        try {
            address = InetAddress.getByName("127.0.0.1");
        } catch (UnknownHostException e) {
            System.out.println(e.getMessage());
        }
        while (true) {

            //发送
            System.out.println("输入发送内容（为空断开连接）：");
            //控制台输入
            Scanner scanner = new Scanner(System.in);
            String str = scanner.nextLine();
            //为空退出
            if (str.equals("")) {
                break;
            }
            //转化
            byte[] buf = str.getBytes();
            try {
                client.send(new DatagramPacket(buf, buf.length, address, port));
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }

            //接收
            receive();

        }
    }

    public void receive() {

        //接收
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);
        try {
            client.receive(dp);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        String str = new String(dp.getData(), 0, dp.getLength());
        System.out.println(dp.getAddress() + ":" + dp.getPort() + "：" + str);

    }
}
